package com.hay.oss.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

@Slf4j
public class FileUtil {

    /**
     * 创建目录
     * @param path 路径
     * @return
     */
    public static boolean makeDirs(String path){
        String dirPath = path.substring(0,path.lastIndexOf("/"));
        File dir = new File(dirPath);
        return dir.exists() || dir.mkdirs();
    }

    /**
     * 创建文件
     * @param fileAbsolutePath 文件绝对路径
     * @param inputStream 流
     * @return
     */
    public static void createFile(String fileAbsolutePath,InputStream inputStream){
        makeDirs(fileAbsolutePath);
        try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(Files.newOutputStream(Paths.get(fileAbsolutePath)))) {
            int len = 0;
            byte[] fileByte = new byte[1024];
            while ((len = inputStream.read(fileByte)) != -1){
                bufferedOutputStream.write(fileByte,0,len);
            }
        }catch (Exception e){
            log.error("createLocalFile error:{},",e.getMessage(),e);
            throw new RuntimeException("本地文件创建失败");
        }
    }

    /**
     * 删除文件
     * @param fileAbsolutePath 文件绝对路径
     * @return
     */
    public static boolean deletedFile(String fileAbsolutePath) {
        File file = new File(fileAbsolutePath);
        if (file.exists()){
            return file.delete();
        }
        return false;
    }

    /**
     * 下载文件
     * @param inputStream
     * @param response
     * @param fileName
     */
    public static void downFile(InputStream inputStream, HttpServletResponse response, String fileName) {
        try(BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream())){
            response.reset();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            String encodedFileName = URLEncoder.encode(getName(fileName), StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
            int length;
            byte[] buf = new byte[1024];
            while((length = inputStream.read(buf)) != -1) {
                out.write(buf, 0, length);
            }
            out.flush();
            out.close();
            inputStream.close();
            response.flushBuffer();
        }catch (Exception e){
            log.error("downFile fileName:{}, error:{},",fileName,e.getMessage(),e);
            throw new RuntimeException("下载失败");
        }
    }

    /**
     * 获取文件后缀名
     * @param fullName 文件名
     * @return 文件后缀名
     */
    public static String getExtension(String fullName) {
        String fileName = getName(fullName);
        int dotIndex = fileName.lastIndexOf(46);
        return dotIndex == -1 ? "" : fileName.substring(dotIndex + 1);
    }

    /**
     * 获取文件名
     * @param fullName 文件名
     * @return 文件名
     */
    public static String getName(String fullName) {
        Assert.hasText(fullName, "file fullName is null.");
        return (new File(fullName)).getName();
    }

}
